package service

import (
	"context"
	"errors"
	"time"

	"goserver/internal/model"
)

type AuthService struct {
	userModel    *model.UserModel
	tokenService *TokenService
}

func NewAuthService(userModel *model.UserModel, tokenService *TokenService) *AuthService {
	return &AuthService{
		userModel:    userModel,
		tokenService: tokenService,
	}
}

type LoginResponse struct {
	Token     string      `json:"token"`
	ExpiresIn int64      `json:"expires_in"` // 过期时间（秒）
	User      *model.User `json:"user"`
}

// Login 用户登录
func (s *AuthService) Login(ctx context.Context, username, password string) (*LoginResponse, error) {
	// 验证用户
	user, err := s.userModel.ValidateUser(ctx, username, password)
	if err != nil {
		return nil, err
	}

	// 检查用户状态
	if user.Status != 1 {
		return nil, errors.New("账号已被禁用")
	}

	// 生成Token
	token, err := s.tokenService.GenerateToken(user.ID)
	if err != nil {
		return nil, err
	}

	return &LoginResponse{
		Token:     token,
		ExpiresIn: 30 * 24 * 3600, // 30天
		User:      user,
	}, nil
}

// Register 用户注册
func (s *AuthService) Register(ctx context.Context, username, password, email string) (*model.User, error) {
	user := &model.User{
		Username: username,
		Password: password,
		Email:    email,
		Status:   1,
	}

	if err := s.userModel.CreateUser(ctx, user); err != nil {
		return nil, err
	}

	return user, nil
}

// Logout 用户登出
func (s *AuthService) Logout(ctx context.Context, token string) error {
	return s.tokenService.RevokeToken(token)
} 